package cn.zwxky.android.user.Utils.chooseimg;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.GridView;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.zgscwjm.lsfbbasetemplate.Event.LsfbEvent;
import com.zgscwjm.lsfbbasetemplate.config.Config;
import com.zgscwjm.lsfbbasetemplate.net.HttpClient;
import com.zgscwjm.lsfbbasetemplate.utils.LsfbLog;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;

import cn.zwxky.android.user.R;
import cn.zwxky.android.user.Utils.LittleUtils;
import cn.zwxky.android.user.Utils.URLString;
import cn.zwxky.android.user.Utils.ZipPic;
import cn.zwxky.android.user.Utils.myProgressDialog;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class ChooseMoreImage extends Activity implements ListImageDirPopupWindow.OnImageDirSelected {

    private ProgressDialog mProgressDialog;
    private myProgressDialog dialog;
    /**
     * 鐎涙ê鍋嶉弬鍥︽婢堕�涜厬閻ㄥ嫬娴橀悧鍥ㄦ殶闁诧拷
     */
    private int mPicsSize;
    /**
     * 閸ュ墽澧栭弫浼村櫤閺堬拷婢舵氨娈戦弬鍥︽婢讹拷
     */
    private File mImgDir;
    /**
     * 閹碉拷閺堝娈戦崶鍓у
     */
    private List<String> mImgs;

    private List<String> getfiles;
    private GridView mGirdView;
    private MyAdapter mAdapter;
    /**
     * 娑撳瓨妞傞惃鍕窡閸斺晝琚敍宀�鏁ゆ禍搴ㄦЩ濮濄垹鎮撴稉锟芥稉顏呮瀮娴犺泛銇欓惃鍕樋濞嗏剝澹傞幓锟�
     */
    private HashSet<String> mDirPaths = new HashSet<String>();

    /**
     * 閹殿偅寮块幏鍨煂閹碉拷閺堝娈戦崶鍓у閺傚洣娆㈡径锟�
     */
    private List<ImageFloder> mImageFloders = new ArrayList<ImageFloder>();

    private RelativeLayout mBottomLy;

    private TextView mChooseDir;
    private TextView mImageCount;
    int totalCount = 0;

    private int mScreenHeight;
    private int maxselectnum = 4;

    private String url;

    private ListImageDirPopupWindow mListImageDirPopupWindow;

    private Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            mProgressDialog.dismiss();
            // 娑撶iew缂佹垵鐣鹃弫鐗堝祦
            data2View();
            // 閸掓繂顫愰崠鏍х潔缁�鐑樻瀮娴犺泛銇欓惃鍒緊pupWindw
            initListDirPopupWindw();
        }
    };

    /**
     * 娑撶iew缂佹垵鐣鹃弫鐗堝祦
     */
    private void data2View() {
        if (mImgDir == null) {
            Toast.makeText(getApplicationContext(), "对不起,没有找到图片",
                    Toast.LENGTH_SHORT).show();
            return;
        }

        mImgs = Arrays.asList(mImgDir.list());
        /**
         * 閸欘垯浜掗惇瀣煂閺傚洣娆㈡径鍦畱鐠侯垰绶為崪灞芥禈閻楀洨娈戠捄顖氱窞閸掑棗绱戞穱婵嗙摠閿涘本鐎径褏娈戦崙蹇撶毌娴滃棗鍞寸�涙娈戝☉
         * 鍫ｏ拷妤嬬幢
         */
        mAdapter = new MyAdapter(getApplicationContext(), mImgs,
                R.layout.browse_grid_item, mImgDir.getAbsolutePath(), maxselectnum);
        mGirdView.setAdapter(mAdapter);
        mImageCount.setText(totalCount + "张");
    }

    ;

    /**
     * 閸掓繂顫愰崠鏍х潔缁�鐑樻瀮娴犺泛銇欓惃鍒緊pupWindw
     */
    private void initListDirPopupWindw() {
        mListImageDirPopupWindow = new ListImageDirPopupWindow(
                LayoutParams.MATCH_PARENT, (int) (mScreenHeight * 0.7),
                mImageFloders, LayoutInflater.from(getApplicationContext())
                .inflate(R.layout.browse_list_dir, null));

        mListImageDirPopupWindow.setOnDismissListener(new OnDismissListener() {

            @Override
            public void onDismiss() {
                // 鐠佸墽鐤嗛懗灞炬珯妫版粏澹婇崣妯绘
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1.0f;
                getWindow().setAttributes(lp);
            }
        });
        // 鐠佸墽鐤嗛柅澶嬪閺傚洣娆㈡径鍦畱閸ョ偠鐨�
        mListImageDirPopupWindow.setOnImageDirSelected(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.browse_activity_main);
        if (getIntent().getStringExtra("url") != null) {
            url = getIntent().getStringExtra("url");
        }
        dialog = new myProgressDialog(this, "上传中，请等待...");
        maxselectnum = getIntent().getIntExtra("num", 9);
        DisplayMetrics outMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
        mScreenHeight = outMetrics.heightPixels;

        initView();
        getImages();
        initEvent();

        findViewById(R.id.activity_main_ok).setOnClickListener(
                new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        if (mAdapter.mSelectedImage.size() > 0) {
                            if (mAdapter.mSelectedImage.size() > maxselectnum) {
                                Toast.makeText(ChooseMoreImage.this,
                                        "最多上传" + maxselectnum + "张图片!", Toast.LENGTH_SHORT).show();
                            } else {
                                dialog.showdialog();
                                // Toast.makeText(ChooseMoreImage.this,
                                // "涓婁紶涓�,璇峰嬁閲嶅鎿嶄綔",
                                // Toast.LENGTH_SHORT).show();
                                upImages(mAdapter.mSelectedImage);
                            }

                        }
                    }
                });

        findViewById(R.id.activity_main_back).setOnClickListener(
                new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        mAdapter.mSelectedImage.clear();
                        ChooseMoreImage.this.finish();
                    }
                });
    }

    private void upImages(List<String> list) {
        // showDialog();
        getfiles = new ArrayList<String>();
        HashMap<String, String> hashMap = new HashMap<String, String>();
        HttpClient client = new HttpClient();
        List<File> list2 = new ArrayList<File>();

        for (int i = 0; i < list.size(); i++) {
            try {
//                Log.e("FFF", list.get(i));
                list2.add(ZipPic.zippng(list.get(i)));
                Log.e("nonsense", i + "*******************************************************************path:" + list2.get(i).getPath());
            } catch (Exception e) {

            }

        }
        hashMap.put("uid", Config.getUserId());
        hashMap.put("img",list2.get(0).getPath());
        client.postFile(url + LittleUtils.getToken(URLString.IMGUPLOAD), hashMap, list2, new Callback() {

            @Override
            public void onResponse(Call arg0, Response arg1) throws IOException {
                // TODO Auto-generated method stub
                dialog.hidedialog();
                if (arg1.isSuccessful()) {

                    String jString = arg1.body().string();
                    LsfbLog.e("上传图片的返回结果" + jString);
                    try {
                        JSONObject jsonObject = new JSONObject(jString);
                        JSONObject img = jsonObject.getJSONObject("data");
                        String mimage = img.getString("img");
                        LsfbEvent.getInstantiation().post(new DuoTuEvent<String>(mimage));
                    } catch (JSONException e) {
                        LsfbLog.e("Json解析错误" + e.getMessage());
                        LittleUtils.closeactivity(ChooseMoreImage.this);
                    }

//                    JSONObject jsonObject = null;
//                    UploadEvent<UploadData> event = new UploadEvent<UploadData>();
//                    try {
//                         jsonObject = new JSONObject(jString);
////                        UploadData data = new UploadData();
////                        data.setData(jsonObject.getString("img"));
////                        LsfbLog.e(jsonObject.getString("img"));
////                        String[] imgs=jsonObject.getString("img").split(",");
////                        for (String imsg:imgs)
////                        {
////                            LsfbLog.e("#################*************"+imsg);
////                        }
////                        event.setData(data);
////                        LsfbEvent.getInstantiation().post(event);
//                        LsfbEvent.getInstantiation().post(new DuoTuEvent<String>(jsonObject.getString("img")));
//                    } catch (Exception e) {
//                        // TODO: handle exceptions
//                        LsfbLog.e("Json解析错误"+e.getMessage());
//                        LittleUtils.closeactivity(ChooseMoreImage.this);
//
//                    }
                }
                LittleUtils.closeactivity(ChooseMoreImage.this);
            }

            @Override
            public void onFailure(Call arg0, IOException arg1) {
                // TODO Auto-generated method stub
                dialog.hidedialog();
                LittleUtils.closeactivity(ChooseMoreImage.this);
            }
        });

    }

    /**
     * 閸掆晝鏁ontentProvider閹殿偅寮块幍瀣簚娑擃厾娈戦崶鍓у閿涘本顒濋弬瑙勭《閸︺劏绻嶇悰灞芥躬鐎涙劗鍤庣粙瀣╄厬
     * 鐎瑰本鍨氶崶鍓у閻ㄥ嫭澹傞幓蹇ョ礉閺堬拷缂佸牐骞忓姊沺g閺堬拷婢舵氨娈戦柇锝勯嚋閺傚洣娆㈡径锟�
     */
    private void getImages() {
        if (!Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            Toast.makeText(this, "暂无外部存储", Toast.LENGTH_SHORT).show();
            return;
        }
        // 閺勫墽銇氭潻娑樺閺夛拷
        mProgressDialog = ProgressDialog.show(this, null, "正在加载...");

        new Thread(new Runnable() {
            @Override
            public void run() {

                String firstImage = null;

                Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                ContentResolver mContentResolver = ChooseMoreImage.this
                        .getContentResolver();

                // 閸欘亝鐓＄拠顣恜eg閸滃ng閻ㄥ嫬娴橀悧锟�
                Cursor mCursor = mContentResolver.query(mImageUri, null,
                        MediaStore.Images.Media.MIME_TYPE + "=? or "
                                + MediaStore.Images.Media.MIME_TYPE + "=?",
                        new String[]{"image/jpeg", "image/png"},
                        MediaStore.Images.Media.DATE_MODIFIED);

                Log.e("TAG", mCursor.getCount() + "");
                while (mCursor.moveToNext()) {
                    // 閼惧嘲褰囬崶鍓у閻ㄥ嫯鐭惧锟�
                    String path = mCursor.getString(mCursor
                            .getColumnIndex(MediaStore.Images.Media.DATA));

                    Log.e("TAG", path);
                    // 閹峰灝鍩岀粭顑跨瀵姴娴橀悧鍥╂畱鐠侯垰绶�
                    if (firstImage == null)
                        firstImage = path;
                    // 閼惧嘲褰囩拠銉ユ禈閻楀洨娈戦悥鎯扮熅瀵板嫬鎮�
                    File parentFile = new File(path).getParentFile();
                    if (parentFile == null)
                        continue;
                    String dirPath = parentFile.getAbsolutePath();
                    ImageFloder imageFloder = null;
                    // 閸掆晝鏁ゆ稉锟芥稉鐙shSet闂冨弶顒涙径姘偧閹殿偅寮块崥灞肩娑擃亝鏋冩禒璺恒仚閿涘牅绗夐崝鐘虹箹娑擃亜鍨介弬顓ㄧ礉閸ュ墽澧栨径姘虫崳閺夈儴绻曢弰顖滄祲瑜版挻浜归幀鏍畱~~閿涳拷
                    if (mDirPaths.contains(dirPath)) {
                        continue;
                    } else {
                        mDirPaths.add(dirPath);
                        // 閸掓繂顫愰崠鏉媘ageFloder
                        imageFloder = new ImageFloder();
                        imageFloder.setDir(dirPath);
                        imageFloder.setFirstImagePath(path);
                    }

                    int picSize = parentFile.list(new FilenameFilter() {
                        @Override
                        public boolean accept(File dir, String filename) {
                            if (filename.endsWith(".jpg")
                                    || filename.endsWith(".png")
                                    || filename.endsWith(".jpeg"))
                                return true;
                            return false;
                        }
                    }).length;
                    totalCount += picSize;

                    imageFloder.setCount(picSize);
                    mImageFloders.add(imageFloder);

                    if (picSize > mPicsSize) {
                        mPicsSize = picSize;
                        mImgDir = parentFile;
                    }
                }
                mCursor.close();

                // 閹殿偅寮跨�瑰本鍨氶敍宀冪窡閸斺晝娈慔ashSet娑旂喎姘ㄩ崣顖欎簰闁插﹥鏂侀崘鍛摠娴滐拷
                mDirPaths = null;

                // 闁氨鐓andler閹殿偅寮块崶鍓у鐎瑰本鍨�
                mHandler.sendEmptyMessage(0x110);

            }
        }).start();
    }

    /**
     * 閸掓繂顫愰崠鏈ew
     */
    private void initView() {
        mGirdView = (GridView) findViewById(R.id.id_gridView);
        mChooseDir = (TextView) findViewById(R.id.id_choose_dir);
        mImageCount = (TextView) findViewById(R.id.id_total_count);

        mBottomLy = (RelativeLayout) findViewById(R.id.id_bottom_ly);

    }

    private void initEvent() {
        /**
         * 娑撳搫绨抽柈銊ф畱鐢啫鐪拋鍓х枂閻愮懓鍤禍瀣╂閿涘苯鑴婇崙绨唎pupWindow
         */
        mBottomLy.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mListImageDirPopupWindow
                        .setAnimationStyle(R.style.anim_popup_dir);
                mListImageDirPopupWindow.showAsDropDown(mBottomLy, 0, 0);

                // 鐠佸墽鐤嗛懗灞炬珯妫版粏澹婇崣妯绘
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = .3f;
                getWindow().setAttributes(lp);
            }
        });

    }

    @Override
    public void selected(ImageFloder floder) {

        mImgDir = new File(floder.getDir());
        mImgs = Arrays.asList(mImgDir.list(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String filename) {
                if (filename.endsWith(".jpg") || filename.endsWith(".png")
                        || filename.endsWith(".jpeg"))
                    return true;
                return false;
            }
        }));
        /**
         * 閸欘垯浜掗惇瀣煂閺傚洣娆㈡径鍦畱鐠侯垰绶為崪灞芥禈閻楀洨娈戠捄顖氱窞閸掑棗绱戞穱婵嗙摠閿涘本鐎径褏娈戦崙蹇撶毌娴滃棗鍞寸�涙娈戝☉
         * 鍫ｏ拷妤嬬幢
         */
        mAdapter = new MyAdapter(getApplicationContext(), mImgs,
                R.layout.browse_grid_item, mImgDir.getAbsolutePath(), maxselectnum);
        mGirdView.setAdapter(mAdapter);
        // mAdapter.notifyDataSetChanged();
        mImageCount.setText(floder.getCount() + "张");
        mChooseDir.setText(floder.getName());
        mListImageDirPopupWindow.dismiss();

    }
//
//	@Override
//	public void onSuccess(JSONObject jsonObject, int accessId) {
//		// TODO Auto-generated method stub
//		mProgressDialog.dismiss();
//		mAdapter.mSelectedImage.clear();
//		Log.e("abc", jsonObject.toString());
//		for (String string : getfiles) {
//			try {
//				File f = new File(string);
//				if (f.exists()) {
//					f.delete();
//					Log.e("DEL", "del:" + string);
//				}
//
//			} catch (Exception e) {
//				// TODO: handle exception
//				Log.e("DEL", "error:" + e);
//			}
//
//		}
//		Intent it = new Intent();
//		try {
//			it.putExtra("img", jsonObject.getString("img"));
//		} catch (JSONException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		// hideDialog();
//		dialog.hidedialog();
//		setResult(Activity.RESULT_OK, it);
//		ChooseMoreImage.this.finish();
//	}
//
//	@Override
//	public void onFailure(HttpException error, String msg, int accessId) {
//		// TODO Auto-generated method stub
//		dialog.hidedialog();
//	}
//
//	@Override
//	public void onStart(int accessId) {
//		// TODO Auto-generated method stub
//
//	}

    // @Override
    // public void onLoading(long total, long current, boolean isUploading) {
    // // TODO Auto-generated method stub
    // if (isUploading) {
    // // 鏉╂稑瀹抽弶锟�
    // // mProgressDialog = ProgressDialog.show(this, null, "濮濓絽婀稉濠佺炊...");
    // Log.e("abc", current + "");
    // }
    // }

    // public void showDialog() {
    // // TODO Auto-generated method stub
    // if(dialog==null)
    // {
    // dialog=new MyDialog(this,R.layout.view_dialog) {
    //
    // @Override
    // public void setRes(Dialog dialog) {
    // // TODO Auto-generated method stub
    // ((TextView)dialog.findViewById(R.id.bewri)).setText("鐠囬鐡戝锟�");
    // }
    // };
    // }
    // dialog.show();
    // }

    // public void hideDialog() {
    // // TODO Auto-generated method stub
    // dialog.hide();
    // }
}
